//
//  TraAppDelegate.m
//  MyAutoTransfer
//
//  Created by wzh on 14-8-14.
//  Copyright (c) 2014年 wzh. All rights reserved.
//

#import "TraAppDelegate.h"
#import "SBJson.h"

NSString* china = @"zh-CN";
NSString* english = @"en";

NSString* jap = @"ja";
NSString* german = @"de";
NSString* eGuo = @"ru";


@implementation TraAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    [self getFiles:NO sourcecountry:english tocountry:eGuo];
    
    return YES;
}

- (void) getFiles:(bool) isSouce sourcecountry:(NSString*) s  tocountry:(NSString*) t
{
    NSString *filePath= @"/Users/wzh/Documents/Transfer/1.txt";
    
    //读取数据
    NSFileHandle *file = [NSFileHandle fileHandleForReadingAtPath:filePath];
    NSData *data = [file readDataToEndOfFile];//读取到NSDate中
    
    NSString* aStr = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];         //转换为NSString
    NSLog( @"aStr is %@", aStr );
    
    [file closeFile];
    
    NSArray* lst = [aStr componentsSeparatedByString:@"\n"];
    
    NSMutableString* lstRet = [[NSMutableString alloc]init];
    
    for (NSString* str in lst) {
        if (str == nil || str.length < 6 || [str rangeOfString:@"="].length == 0
            || [str rangeOfString:@"//"].length > 0) {
            [lstRet appendString:str];
            [lstRet appendString:@"\n"];
            continue;
        }
        
        if (isSouce) {
            [lstRet appendString:@"//"];
            [lstRet appendString:str];
            [lstRet appendString:@"\n"];
        }
        
       
        
        NSString* str1  = [str stringByReplacingOccurrencesOfString:@";" withString:@""];

        str1  = [str1 stringByReplacingOccurrencesOfString:@"\"" withString:@""];
      
        NSRange range = [str1 rangeOfString:@"="];
        
        NSString* firstStr = [[str1 substringToIndex:range.location] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
        
        NSString* lastStr = [[str1 substringFromIndex:range.location+1] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
        
        NSString* result = [self Transfer:lastStr sourcecountry:s tocountry:t];
        
        NSString* newRecord = [NSString stringWithFormat:@"\"%@\" = \"%@\";\n",firstStr, result];
        
        
        [lstRet appendString:newRecord];
        [lstRet appendString:@"\n"];

        
    }
    
    NSLog(@"%@", lstRet);

    [self writeToFile:lstRet];
}

- (void) writeToFile:(NSString *)data {
    
    //指向文件目录
    NSString *filePath= @"/Users/wzh/Documents/Transfer/2.txt";
    
    [[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
    
    FILE *file = fopen([filePath UTF8String], [@"ab+" UTF8String]);
    
    if(file != NULL){
        fseek(file, 0, SEEK_END);
    }
    
    NSData * outData=[data dataUsingEncoding:NSUTF8StringEncoding];
    
    int readSize = (int)[outData length];
    fwrite((const void *)[outData bytes], readSize, 1, file);
    fclose(file);
    
}


-(NSString* ) Transfer:(NSString*) q  sourcecountry:(NSString*) s  tocountry:(NSString*) t
{
    NSString* url = @"http://translate.google.cn/translate_a/single?";
    NSString* guPara = @"client=t&ie=UTF-8&op=UTF-8&dt=bd&dt=ex&dt=ld&dt=md&dt=qc&dt=rw&dt=rm&dt=ss&dt=t&dt=at&dt=sw";
    

    
    NSString *requestString = [NSString stringWithFormat:@"%@q=%@&sl=%@&tl=%@&%@",url,[self urlEncode:q], s, t, guPara];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:requestString]];

    NSData *data = [self dataWithRequest:request isPost:YES];
    if (data == nil) {
        return NO;
    }
    
    NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    if(html == nil){
        return nil;
    }
    
    NSString* str1 = [html substringFromIndex:4];
    NSRange range = [str1 rangeOfString:@"\",\""];

    NSString* str2= [str1 substringToIndex:range.location];

    return  str2;
}

- (NSString *)urlEncode:(NSString *)str
{
    if (str.length == 0) return nil;
       NSString *encodedString = (NSString *) CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes( NULL, (CFStringRef)str, NULL, (CFStringRef)@"!*'();:@&=+$,/?%#[]", kCFStringEncodingUTF8 ));
    return encodedString;
}


// http 请求
- (NSData *)dataWithRequest:(NSMutableURLRequest *)request isPost:(BOOL)isPost;
{
    [request setHTTPShouldHandleCookies:YES];
    if (_cookie) {
        [request setValue:_cookie forHTTPHeaderField:@"Set-Cookie"];
    }

    if (isPost) {
        [request setHTTPMethod:@"POST"];
    } else {
        [request setHTTPMethod:@"GET"];
    }
    [request setValue:@"XMLHttpRequest" forHTTPHeaderField:@"x-requested-with"];
    
    //    [request setValidatesSecureCertificate:NO];
    
    NSDictionary *requestFields = [request allHTTPHeaderFields];
    NSLog(@"Request:%@", [requestFields description]);
    
    
    NSURLResponse *response = nil;
    NSError *error = nil;
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    if (error) {
        return nil;
    }
    
    NSHTTPURLResponse *HTTPResponse = (NSHTTPURLResponse *)response;
    if (HTTPResponse) {
        NSDictionary *responseFields = [HTTPResponse allHeaderFields];
        NSLog(@"Response:%@", [responseFields description]);
        
        NSString *cookie = [responseFields valueForKey:@"Set-Cookie"];
        if ([cookie length] > 0) {
            self.cookie = cookie;
        }
    }
    
    return data;
}




- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
